package com.allm.ai.common.strategy.impl;

import com.allm.ai.common.entity.AiModel;
import com.allm.ai.common.dto.ApiRequest;
import com.allm.ai.common.strategy.AiModelStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@SuppressWarnings("unchecked")
public class AnthropicStrategy implements AiModelStrategy {
    
    private final RestTemplate restTemplate = new RestTemplate();
    
    @Override
    public String callApi(AiModel model, ApiRequest request) throws Exception {
        log.info("调用 Anthropic API，模型: {}, 端点: {}", model.getName(), model.getApiEndpoint());
        
        // 构建 Anthropic API 请求
        Map<String, Object> apiRequest = new HashMap<>();
        apiRequest.put("model", model.getName());
        apiRequest.put("max_tokens", request.getMaxTokens());
        apiRequest.put("temperature", request.getTemperature());
        apiRequest.put("messages", buildAnthropicMessages(request.getMessages()));
        
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("x-api-key", model.getApiKey());
        headers.set("anthropic-version", "2023-06-01");
        
        // 发送请求
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(apiRequest, headers);
        
        try {
            ResponseEntity<Map> response = restTemplate.postForEntity(
                model.getApiEndpoint(), 
                entity, 
                Map.class
            );
            
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                Map<String, Object> responseBody = response.getBody();
                
                // 解析 Anthropic 响应
                if (responseBody.containsKey("content") && responseBody.get("content") instanceof java.util.List) {
                    java.util.List<Map<String, Object>> contentList = (java.util.List<Map<String, Object>>) responseBody.get("content");
                    if (!contentList.isEmpty()) {
                        Map<String, Object> firstContent = contentList.get(0);
                        if (firstContent.containsKey("text")) {
                            return (String) firstContent.get("text");
                        }
                    }
                }
                
                // 如果没有找到预期的响应格式，返回原始响应
                log.warn("Anthropic API 响应格式异常: {}", responseBody);
                return "Anthropic API 响应格式异常: " + responseBody.toString();
            } else {
                throw new RuntimeException("Anthropic API 请求失败，状态码: " + response.getStatusCode());
            }
            
        } catch (Exception e) {
            log.error("调用 Anthropic API 失败", e);
            throw new RuntimeException("Anthropic API 调用失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 构建 Anthropic 消息格式
     */
    private java.util.List<Map<String, Object>> buildAnthropicMessages(java.util.List<Map<String, Object>> messages) {
        java.util.List<Map<String, Object>> anthropicMessages = new java.util.ArrayList<>();
        
        for (Map<String, Object> message : messages) {
            Map<String, Object> anthropicMessage = new HashMap<>();
            anthropicMessage.put("role", convertRole(message.get("role")));
            anthropicMessage.put("content", message.get("content"));
            anthropicMessages.add(anthropicMessage);
        }
        
        return anthropicMessages;
    }
    
    /**
     * 转换角色格式
     */
    private String convertRole(Object role) {
        String roleStr = String.valueOf(role);
        if ("user".equals(roleStr)) {
            return "user";
        } else if ("assistant".equals(roleStr)) {
            return "assistant";
        } else if ("system".equals(roleStr)) {
            return "user"; // Anthropic 没有 system 角色，转换为 user
        }
        return "user";
    }
    
    @Override
    public boolean supports(String serviceProvider) {
        return "anthropic".equalsIgnoreCase(serviceProvider) || 
               "claude".equalsIgnoreCase(serviceProvider);
    }
    
    @Override
    public boolean supportsStreaming() {
        return false;
    }

}